<template>
  <div class="login-container">
    <template>
      <div class="login-container">
        <van-nav-bar title="登录">
          <template #left>
            <img class="logo" src="@/assets/images/logo.png" />
          </template>
        </van-nav-bar>
        <van-form @submit="onSubmit">
          <van-field
            v-model="formLogin.mobile"
            type="tel"
            name="mobile"
            label="手机号"
            placeholder="请输入手机号"
            required
            :rules="[
              {
                required: true,
                message: '请填写手机号',
                trigger: 'onChange',
                pattern: /^1[3456789]\d{9}$/,
              },
            ]"
          />
          <van-field
            v-model="formLogin.code"
            type="password"
            label="密码"
            name="code"
            placeholder="请输入密码"
            required
            :rules="[
              {
                required: true,
                message: '请填写密码',
                trigger: 'onChange',
                pattern: /^\d{6}$/,
              },
            ]"
          />
          <div style="margin: 16px">
            <van-button round block type="info" native-type="submit" :loading="isLoading" loading-text="程序员拼命加载ing...">登录</van-button>
          </div>
        </van-form>
      </div>
    </template>
  </div>
</template>

<script>
import { LoginAPI } from '../../api/login'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['settoken', 'setrefreshtoken']),
    async onSubmit () {
      try {
        this.isLoading = true
        const res = await LoginAPI(this.formLogin)
        console.log(res)
        this.settoken(res.data.token)
        this.setrefreshtoken(res.data.refresh_token)
        Notify({ type: 'success', message: '登陆成功' })
        this.$router.push({
          path: this.$route.query.from || '/layout'
        })
      } catch {
        Notify({ type: 'danger', message: '用户名密码不正确' })
      } finally {
        this.isLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
